/*
 * Copyright 2020-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hhq.sso.protocol.oauth2.web;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hhq.sso.protocol.oauth2.constants.CommonConstant;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Steve Riesenberg
 * @since 1.1
 */
@Controller
public class LoginController {

    @Autowired
    private DefaultKaptcha kaptcha;

    @GetMapping("/login")
    public String login() {
        return "login";
    }


    /**
     * 生成验证码接口
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 将验证码文本存储在 session 中，后续验证时需要使用
        String text = kaptcha.createText();
        request.getSession().setAttribute(CommonConstant.CAPTCHA_SESSION_KEY, text);
        BufferedImage image = kaptcha.createImage(text);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(image, "png", outputStream);
        }
    }

}
